<?php
namespace app\index\controller;
use think\Controller;
use think\Db;

class Pay extends Controller
{
	/**
    * 初始化
    */
    public function _initialize() {
        //引入WxPayPubHelper
        vendor('WxPayPubHelper.WxPayPubHelper');
    }
	
	//支付成功页面
	function jsapi_data(){
		
	}
   
   
   //【接下来是使用统一支付接口，获取prepay_id的方法：】
	 public function jsapi() {

        $param = input('param.');
        
        // 
        if(empty($param['type'])){
            //tg推广   fk房卡
            return $this->error('参数错误');
        }else{
            $num = substr($param['type'],2);
            $type = substr($param['type'],0,2);
        }
        
        if($type == 'tg'){//推广码
            $money = db('qrcode_money')->where(['id'=>1])->value('money');
            $money = $money*100;
        }elseif ($type == 'fk') {
            $money = db('game_money')->where(['id'=>1])->value('money');
            $money = $money*100*$num;
        }else{
           return $this->error('参数错误2'); 
        }
        

         $money = 1;
        // dump($money);exit;
        //使用jsapi接口
        $jsApi = new \JsApi_pub();
        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
		$openid =null;
        if (!isset($_GET['code'])) {
            //触发微信返回code码
			$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";		
			$redirectUrl = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $url = $jsApi->createOauthUrlForCode($redirectUrl);
            Header("Location: $url");
        } else {
			$openid = session("openid");
            //获取code码，以获取openid
			if(!$openid){
				
				//$this->redirect(url('pay/jsapi'));
				$code = $_GET['code'];
				$jsApi->setCode($code);
				$openid = $jsApi->getOpenId();
			}
            
        }
		session("openid",$openid);

		//生成唯一订单号
		$build_order_no = $this->build_order_no();

        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $Order = new \UnifiedOrder_pub();
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $Order->setParameter("openid",$openid);//商品描述
        $Order->setParameter("body","ydqp");//商品描述
        //自定义订单号，此处仅作举例
        $out_trade_no = $this->build_order_no();
        $Order->setParameter("out_trade_no",$out_trade_no);//商户订单号
        // $Order->setParameter("total_fee",  (98)*100 );  //总金额 1   
	    $Order->setParameter("total_fee",$money);  //总金额 1 
		$notify_url ='http://client.rup-china.com/yxzf/index.php/index/pay/notify';
        $Order->setParameter("notify_url",$notify_url);//通知地址
        $Order->setParameter("trade_type","JSAPI");//交易类型
        //非必填参数，商户可根据实际情况选填
        //$Order->setParameter("sub_mch_id","XXXX");//子商户号
        //$Order->setParameter("device_info","XXXX");//设备号
        $Order->setParameter("attach",$type);//附加数据
        //$Order->setParameter("time_start","XXXX");//交易起始时间
        //$Order->setParameter("time_expire","XXXX");//交易结束时间
        $Order->setParameter("goods_tag",$num);//商品标记
        //$Order->setParameter("openid","XXXX");//用户标识
        $Order->setParameter("product_id",$out_trade_no);//商品ID
        $prepay_id = $Order->getPrepayId();
        
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);
        $jsApiParameters = $jsApi->getParameters();
		
        $this->assign('jsApiParameters',$jsApiParameters);
		$this->assign('type',$type);
        $this->assign('money',$money);
		
		$obj = \think\loader::controller('index/index');
		$this->assign('signPackage',$obj->getSignPackage());
        $data = '';
        if($type == 'fk'){
		  $id = db('fk_order')->insertGetId(['order_id'=>$out_trade_no,'openid'=>$openid,'out_trade_no'=>$out_trade_no,'total_fee'=>$money,'attach'=>$type,'goods_tag'=>$num,'time'=>date('Y-m-d H:i:s')]);
          $gameid = session('gameid');
          $userid = session('userid');
          
          $data = 'userid='.$userid.'&gameid='.$gameid.'&buycount='.$num.'&payamount='.$money;
          // $data = 'userid=5&gameid=100105&buycount=10&payamount=1';
          
          
        }elseif ($type == 'tg') {
          $id = db('tg_order')->insertGetId(['order_id'=>$out_trade_no,'openid'=>$openid,'out_trade_no'=>$out_trade_no,'total_fee'=>$money,'attach'=>$type,'goods_tag'=>$num,'time'=>date('Y-m-d H:i:s')]);
        }

        $this->assign('id',$id); 
        $this->assign('data',$data);

        return $this->fetch();
    }
	
	
	//【步通知方法，也是复制的微信demo上的】
	 public function notify() {
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
		
		$log_name= "public/log/notify_url.log";//log文件路径
        $xml = $GLOBALS["HTTP_RAW_POST_DATA"]; 
		//以log文件形式记录回调信息
        $this->log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");
		
		$notify->saveData($xml);
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();

        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                $this->log_result($log_name,"【通信出错】:\n".$xml."\n");
            }
            elseif($notify->data["result_code"] == "FAIL"){
                //此处应该更新一下订单状态，商户自行增删操作
                $this->log_result($log_name,"【业务出错】:\n".$xml."\n");
            }
            else{
                //此处应该更新一下订单状态，商户自行增删操作
                $this->log_result($log_name,"【支付成功】:\n".$xml."\n");
				//商户自行增加处理流程,
				//例如：更新订单状态
				//例如：数据库操作
				//例如：推送支付完成信息
				$this->saveOrder( $notify );//记录支付情况
                //记录
                if($notify->data["attach"] == 'fk'){
                    $this->fk_order($notify);
                    $obj = \think\loader::controller('index/index');
                    $frist_data_openid = db('collaborator')->where(['openid'=>$notify->data["openid"]])->value('first_openid');
                    $obj->fk_Message($frist_data_openid,$notify->data["total_fee"]);//通知
                }elseif ($notify->data["attach"] == 'tg') {
                    $this->tg_order($notify);
                }

                //给推广者加钱
                $frist_data_openid = db('collaborator')->where(['openid'=>$notify->data["openid"]])->value('first_openid');
                if(!empty($frist_data_openid)){
                    $money = db('weixin_user')->where(['openid'=>$frist_data_openid])->value('money');
                    $money += $notify->data["total_fee"];
                    db('weixin_user')->where(['openid'=>$frist_data_openid])->update(['money'=>$money]);
                }

                //通知Java方
                $data = db('fk_order')->where(['order_id'=>$notify->data["out_trade_no"]])->value('data');
                if(!empty($data)){
                    $url = 'http://www.hanqp.com:8088/api/inotify/done?token='.$data;
                    $this->request_post($url,$data);
                }
                
                
                
                
            } 
        }
    }
	
	function saveOrder( $notify ){
		$ret = Db('order')->where('out_trade_no', $notify->data["out_trade_no"] )->find();
		//避免微信重复提醒导致数据不正确
		if(!$ret){
			$order_data['order_id'] = $notify->data["out_trade_no"];
			//$order_data['product_id'] = $notify->data["product_id"];
			
			$order_data['bank_type'] = $notify->data["bank_type"];
			$order_data['cash_fee'] = $notify->data["cash_fee"];
			$order_data['fee_type'] = $notify->data["fee_type"];
			$order_data['openid'] = $notify->data["openid"]; 
			$order_data['mch_id'] = $notify->data["mch_id"];
			$order_data['out_trade_no'] = $notify->data["out_trade_no"];
			$order_data['transaction_id'] = $notify->data["transaction_id"];
			$order_data['time_end'] = $notify->data["time_end"];
			$order_data['total_fee'] = $notify->data["total_fee"];
            $order_data['attach'] = $notify->data["attach"];
			$order_data['create_time'] = Date('Y-m-d H:i:s',time());
			
			Db('order')->insertGetId( $order_data );
		}
	}

    //房卡购买判断
    public function fk_order($notify){
        $data = db('fk_order')->where(['openid'=>$notify->data["openid"],'out_trade_no'=>$notify->data["out_trade_no"]])->find();
        if($data['total_fee'] == $notify->data["total_fee"]){
            db('fk_order')->where(['openid'=>$notify->data["openid"],'out_trade_no'=>$notify->data["out_trade_no"]])->update(['state'=>1]);
        }
    }

    //推广购买判断
    public function tg_order($notify){
        $data = db('tg_order')->where(['openid'=>$notify->data["openid"],'out_trade_no'=>$notify->data["out_trade_no"]])->find();
        if($data['total_fee'] == $notify->data["total_fee"]){
            db('tg_order')->where(['openid'=>$notify->data["openid"],'out_trade_no'=>$notify->data["out_trade_no"]])->update(['state'=>1]);
        }
    }

     //模拟post提交
    function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        
        $postUrl = $url;
        $curlPost = '';
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
    }


    public function get_data(){
        $param = input('param.');
        // return $param['id'];
        $num = db('fk_order')->where(['id'=>$param['id']])->update(['data'=>$param['data']]);
        return $num;
        
    }

    public function test(){
        $url = 'http://www.hanqp.com:8088/api/inotify/done?token=sCDk2mdU7fEu3K2H/vNCWz8coliwpY+MxHAt3BAusYpMnusa495NVarlUE81O+sb';
        // $url = 'http://client.rup-china.com/yxzf/index.php/index/pay/test_post';
        $param['token'] = '3Zopcl0LCzz6cl/9QyRXn1OR/LEFsk511Mfy51F1BLgHNYIg/l5S2vLoTr+KxECm';
        if (empty($url) || empty($param)) {
            return false;
        }
        
        $postUrl = $url;
        // $curlPost = $param;
        $curlPost = '';
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
        // dump($data);
    }

    public function test_post(){
        $param = input('post.');

        return json($param['token']);
    }












	
	
	function  log_result($file,$word) {
		if(!file_exists($file)){
			mkdir($file);
		}
		$fp = fopen($file,"a");
		flock($fp, LOCK_EX) ;
		fwrite($fp,"执行日期：".strftime("%Y-%m-%d-%H：%M：%S",time())."\n".$word."\n\n");
		flock($fp, LOCK_UN);
		fclose($fp);
	}
	
	/**
    * 生成唯一订单号
    */
    public function build_order_no() {
        $order_id = date('Ydy').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))) , 0, 8); 
        $data = db('pay_order')->where(['order_id'=>$order_id])->find();
        if(!empty($data)){
        	$this->build_order_no();
        }else{
        	return $order_id;
        }
    }
	
	
	
}
?>